package org.simplextensions.scanner;

import javassist.bytecode.ClassFile;

import java.util.*;
import java.util.Map.Entry;

public abstract class ClassScannerBundle {

	private final Map<String, Map<Integer, List<IClassScanner>>> scanListeners;
	private final Set<String> classNames;
	private final String name;

	public ClassScannerBundle(String name, Map<String, Map<Integer, List<IClassScanner>>> scanListeners, Set<String> classNames) {
		this.name = name;
		this.scanListeners = scanListeners;
		this.classNames = classNames != null ? new HashSet<String>(classNames) : new HashSet<String>();
	}

	public abstract Iterator<ClassFile> classFileIterator();

	public String getName() {
		return name;
	}

	public Set<String> getClassNames() {
		return Collections.unmodifiableSet(classNames);
	}

	public List<IClassScanner> getScanListeners() {
		List<IClassScanner> result = new LinkedList<IClassScanner>();

		Map<Integer, List<IClassScanner>> scannersMap = new HashMap<Integer, List<IClassScanner>>();

		for (Map<Integer, List<IClassScanner>> map : this.scanListeners.values()) {
			for (Entry<Integer, List<IClassScanner>> e : map.entrySet()) {
				List<IClassScanner> list = scannersMap.get(e.getKey());
				if (list == null) {
					scannersMap.put(e.getKey(), list = new LinkedList<IClassScanner>());
				}
				list.addAll(e.getValue());
			}
		}

		for (List<IClassScanner> l : scannersMap.values()) {
			result.addAll(l);
		}
		return result;
	}

}
